import urllib.request
from lxml import etree


# 获取网页源码

# 下载

# 下载前十页的情侣图片
# https://sc.chinaz.com/tupian/qinglvtupian.html

def create_request(page):
    if (page == 1):
        url = "https://sc.chinaz.com/tupian/qinglvtupian.html"
    else:
        url = "https://sc.chinaz.com/tupian/qinglvtupian_" + str(page) + ".html"

    headers = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
    }
    return urllib.request.Request(url=url, headers=headers)


def get_content(request):
    response = urllib.request.urlopen(request)
    return response.read().decode('utf-8')


def down_load(content):
    # 下载图片
    tree = etree.HTML(content)

    name_list = tree.xpath('//div[@class="container"]//img/@alt')

    # 设计图片的网站会有懒加载
    src_list = tree.xpath('//div[@class="container"]//img/@data-original')

    for i in range(len(name_list)):
        name=name_list[i]
        src=src_list[i]
        url="https:"+src
        urllib.request.urlretrieve(url=url,filename='../pages/'+name+'.jpg')


if __name__ == '__main__':
    for page in range(1, 6):
        # 请求对象的定制
        print('获取第' + str(page) + '页数据')
        request = create_request(page)

        content = get_content(request)

        down_load(content)
        print('=================================')
